from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save


# Create your models here.
class NoticeModel(models.Model):
    class Meta:
        db_table = "notice"
        verbose_name = "通知"
        verbose_name_plural = verbose_name

    title = models.CharField(max_length=100, verbose_name="标题")
    content = models.TextField(verbose_name="内容")
    notice_type = models.CharField(max_length=50, default='', blank=True,verbose_name="类型")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    creater = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="创建人", related_name="create_notices",
                             db_index=True)
    members = models.ManyToManyField(to=User, verbose_name="成员", through='NoticeMembersModel', related_name='Notices')
    def __str__(self):
        return self.title

class NoticeMembersModel(models.Model):
    class Meta:
        db_table = "notice_members"
        verbose_name = "通知成员"
        verbose_name_plural = verbose_name

    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户", related_name="joined_notices",
                             db_index=True)
    notice = models.ForeignKey(NoticeModel, on_delete=models.CASCADE, verbose_name="通知")
    time = models.DateTimeField(auto_now_add=True, verbose_name="加入时间")
    done = models.BooleanField(default=False,verbose_name="已读")


def create_notice_members(sender, instance, created, **kwargs):
    if created:
        if instance.notice_type == "all":
            users = User.objects.all()
            for user in users:
                NoticeMembersModel.objects.create(user=user, notice=instance)


post_save.connect(create_notice_members, sender=NoticeModel)
